#include "core/enhanced_chat_system.h"
#include <random>
#include <algorithm>
#include <sstream>
#include <sys/socket.h>

// ==================== 用户管理 ====================

bool EnhancedChatSystem::addUser(const std::string& userId, int socketFd, const std::string& ip) {
    std::lock_guard<std::mutex> lock(usersMutex);
    
    // 检查用户是否已存在
    if (users.find(userId) != users.end()) {
        return false;
    }
    
    // 创建用户信息
    auto user = std::make_shared<UserInfo>(userId, socketFd, ip);
    users[userId] = user;
    socketToUser[socketFd] = userId;
    
    return true;
}

void EnhancedChatSystem::removeUser(const std::string& userId) {
    std::lock_guard<std::mutex> lock(usersMutex);
    
    auto it = users.find(userId);
    if (it != users.end()) {
        // 从socket映射中移除
        socketToUser.erase(it->second->socketFd);
        // 移除用户
        users.erase(it);
    }
}

std::shared_ptr<UserInfo> EnhancedChatSystem::getUser(const std::string& userId) {
    std::lock_guard<std::mutex> lock(usersMutex);
    auto it = users.find(userId);
    return (it != users.end()) ? it->second : nullptr;
}

std::vector<std::shared_ptr<UserInfo>> EnhancedChatSystem::getOnlineUsers() {
    std::lock_guard<std::mutex> lock(usersMutex);
    std::vector<std::shared_ptr<UserInfo>> onlineUsers;
    
    for (const auto& pair : users) {
        if (pair.second->status == STATUS_ONLINE) {
            onlineUsers.push_back(pair.second);
        }
    }
    
    return onlineUsers;
}

// ==================== 私聊管理 ====================

std::string EnhancedChatSystem::generateChatId(const std::string& user1, const std::string& user2) {
    // 按字典序排序确保聊天ID的唯一性
    if (user1 < user2) {
        return user1 + "_" + user2;
    } else {
        return user2 + "_" + user1;
    }
}

std::string EnhancedChatSystem::startPrivateChat(const std::string& user1, const std::string& user2) {
    std::lock_guard<std::mutex> lock(chatsMutex);
    
    std::string chatId = generateChatId(user1, user2);
    
    // 检查私聊是否已存在
    if (privateChats.find(chatId) == privateChats.end()) {
        // 创建新的私聊会话
        auto chat = std::make_shared<PrivateChat>(user1, user2);
        privateChats[chatId] = chat;
        
        // 更新用户的私聊列表
        {
            std::lock_guard<std::mutex> userLock(usersMutex);
            auto userInfo1 = users.find(user1);
            auto userInfo2 = users.find(user2);
            
            if (userInfo1 != users.end()) {
                userInfo1->second->privateChats.insert(chatId);
            }
            if (userInfo2 != users.end()) {
                userInfo2->second->privateChats.insert(chatId);
            }
        }
    }
    
    return chatId;
}

bool EnhancedChatSystem::sendPrivateMessage(const std::string& fromUser, const std::string& toUser, const std::string& content) {
    // 确保私聊会话存在
    std::string chatId = startPrivateChat(fromUser, toUser);
    
    // 创建消息
    EnhancedMessage msg;
    msg.type = MSG_PRIVATE_CHAT;
    msg.messageId = generateId();
    msg.fromUser = fromUser;
    msg.toUser = toUser;
    msg.content = content;
    msg.timestamp = time(nullptr);
    msg.chatType = CHAT_PRIVATE;
    
    // 保存消息到会话历史
    {
        std::lock_guard<std::mutex> lock(chatsMutex);
        auto chatIt = privateChats.find(chatId);
        if (chatIt != privateChats.end()) {
            chatIt->second->messages.push_back(msg);
            chatIt->second->lastActiveTime = time(nullptr);
        }
    }
    
    // 发送消息给接收者
    sendToUser(toUser, msg);
    
    return true;
}

std::shared_ptr<PrivateChat> EnhancedChatSystem::getPrivateChat(const std::string& user1, const std::string& user2) {
    std::lock_guard<std::mutex> lock(chatsMutex);
    
    std::string chatId = generateChatId(user1, user2);
    auto it = privateChats.find(chatId);
    return (it != privateChats.end()) ? it->second : nullptr;
}

// ==================== 群组管理 ====================

std::string EnhancedChatSystem::createGroup(const std::string& groupName, const std::string& ownerId, const std::string& description) {
    std::lock_guard<std::mutex> lock(groupsMutex);
    
    std::string groupId = generateId();
    auto group = std::make_shared<GroupInfo>(groupId, groupName, ownerId);
    group->description = description;
    
    groups[groupId] = group;
    
    // 更新群主的群组列表
    {
        std::lock_guard<std::mutex> userLock(usersMutex);
        auto userIt = users.find(ownerId);
        if (userIt != users.end()) {
            userIt->second->groups.insert(groupId);
        }
    }
    
    return groupId;
}

bool EnhancedChatSystem::joinGroup(const std::string& groupId, const std::string& userId) {
    std::lock_guard<std::mutex> lock(groupsMutex);
    
    auto groupIt = groups.find(groupId);
    if (groupIt == groups.end()) {
        return false;
    }
    
    // 添加成员
    if (!groupIt->second->addMember(userId)) {
        return false; // 群组已满
    }
    
    // 更新用户的群组列表
    {
        std::lock_guard<std::mutex> userLock(usersMutex);
        auto userIt = users.find(userId);
        if (userIt != users.end()) {
            userIt->second->groups.insert(groupId);
        }
    }
    
    return true;
}

bool EnhancedChatSystem::leaveGroup(const std::string& groupId, const std::string& userId) {
    std::lock_guard<std::mutex> lock(groupsMutex);
    
    auto groupIt = groups.find(groupId);
    if (groupIt == groups.end()) {
        return false;
    }
    
    // 群主不能离开群组，只能解散
    if (groupIt->second->ownerId == userId) {
        return false;
    }
    
    // 移除成员
    groupIt->second->removeMember(userId);
    
    // 更新用户的群组列表
    {
        std::lock_guard<std::mutex> userLock(usersMutex);
        auto userIt = users.find(userId);
        if (userIt != users.end()) {
            userIt->second->groups.erase(groupId);
        }
    }
    
    return true;
}

bool EnhancedChatSystem::sendGroupMessage(const std::string& groupId, const std::string& fromUser, const std::string& content) {
    std::shared_ptr<GroupInfo> group;
    {
        std::lock_guard<std::mutex> lock(groupsMutex);
        auto groupIt = groups.find(groupId);
        if (groupIt == groups.end()) {
            return false;
        }
        group = groupIt->second;
    }
    
    // 检查用户是否为群成员
    if (!group->isMember(fromUser)) {
        return false;
    }
    
    // 创建群消息
    EnhancedMessage msg;
    msg.type = MSG_GROUP_CHAT;
    msg.messageId = generateId();
    msg.fromUser = fromUser;
    msg.groupId = groupId;
    msg.content = content;
    msg.timestamp = time(nullptr);
    msg.chatType = CHAT_GROUP;
    
    // 保存消息到群组历史
    {
        std::lock_guard<std::mutex> lock(groupsMutex);
        auto groupIt = groups.find(groupId);
        if (groupIt != groups.end()) {
            groupIt->second->messages.push_back(msg);
        }
    }
    
    // 广播消息给群成员
    broadcastToGroup(groupId, msg, fromUser);
    
    return true;
}

bool EnhancedChatSystem::inviteToGroup(const std::string& groupId, const std::string& inviterId, const std::string& inviteeId) {
    std::lock_guard<std::mutex> lock(groupsMutex);
    
    auto groupIt = groups.find(groupId);
    if (groupIt == groups.end()) {
        return false;
    }
    
    // 检查邀请者是否为管理员
    if (!groupIt->second->isAdmin(inviterId)) {
        return false;
    }
    
    // 检查被邀请者是否已是群成员
    if (groupIt->second->isMember(inviteeId)) {
        return false;
    }
    
    // 发送邀请消息给被邀请者
    EnhancedMessage inviteMsg;
    inviteMsg.type = MSG_INVITE_TO_GROUP;
    inviteMsg.messageId = generateId();
    inviteMsg.fromUser = inviterId;
    inviteMsg.toUser = inviteeId;
    inviteMsg.groupId = groupId;
    inviteMsg.content = "You have been invited to join group: " + groupIt->second->groupName;
    inviteMsg.timestamp = time(nullptr);
    
    sendToUser(inviteeId, inviteMsg);
    
    return true;
}

std::shared_ptr<GroupInfo> EnhancedChatSystem::getGroup(const std::string& groupId) {
    std::lock_guard<std::mutex> lock(groupsMutex);
    auto it = groups.find(groupId);
    return (it != groups.end()) ? it->second : nullptr;
}

std::vector<std::shared_ptr<GroupInfo>> EnhancedChatSystem::getUserGroups(const std::string& userId) {
    std::vector<std::shared_ptr<GroupInfo>> userGroups;
    std::unordered_set<std::string> groupIds;
    
    // 获取用户的群组ID列表
    {
        std::lock_guard<std::mutex> userLock(usersMutex);
        auto userIt = users.find(userId);
        if (userIt != users.end()) {
            groupIds = userIt->second->groups;
        }
    }
    
    // 获取群组信息
    std::lock_guard<std::mutex> groupLock(groupsMutex);
    for (const std::string& groupId : groupIds) {
        auto groupIt = groups.find(groupId);
        if (groupIt != groups.end()) {
            userGroups.push_back(groupIt->second);
        }
    }
    
    return userGroups;
}

// ==================== 消息路由 ====================

void EnhancedChatSystem::routeMessage(const EnhancedMessage& message) {
    switch (message.type) {
        case MSG_PRIVATE_CHAT:
            sendPrivateMessage(message.fromUser, message.toUser, message.content);
            break;
            
        case MSG_GROUP_CHAT:
            sendGroupMessage(message.groupId, message.fromUser, message.content);
            break;
            
        case MSG_JOIN_GROUP:
            joinGroup(message.groupId, message.fromUser);
            break;
            
        case MSG_LEAVE_GROUP:
            leaveGroup(message.groupId, message.fromUser);
            break;
            
        default:
            // 处理其他消息类型
            break;
    }
}

void EnhancedChatSystem::sendToUser(const std::string& userId, const EnhancedMessage& message) {
    std::shared_ptr<UserInfo> user;
    {
        std::lock_guard<std::mutex> lock(usersMutex);
        auto userIt = users.find(userId);
        if (userIt == users.end() || userIt->second->status == STATUS_OFFLINE) {
            return; // 用户不存在或离线
        }
        user = userIt->second;
    }
    
    // 发送消息到用户的socket
    std::string data = message.serialize();
    send(user->socketFd, data.c_str(), data.length(), 0);
    
    // 更新用户活跃时间
    updateUserActivity(userId);
}

void EnhancedChatSystem::broadcastToGroup(const std::string& groupId, const EnhancedMessage& message, const std::string& excludeUser) {
    std::shared_ptr<GroupInfo> group;
    {
        std::lock_guard<std::mutex> lock(groupsMutex);
        auto groupIt = groups.find(groupId);
        if (groupIt == groups.end()) {
            return;
        }
        group = groupIt->second;
    }
    
    // 向群组所有成员发送消息（除了排除的用户）
    for (const std::string& memberId : group->members) {
        if (memberId != excludeUser) {
            sendToUser(memberId, message);
        }
    }
}

// ==================== 工具方法 ====================

std::string EnhancedChatSystem::generateId() {
    // 生成唯一ID（时间戳 + 随机数）
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_int_distribution<> dis(1000, 9999);
    
    auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
        std::chrono::system_clock::now().time_since_epoch()).count();
    
    return std::to_string(now) + "_" + std::to_string(dis(gen));
}

bool EnhancedChatSystem::isUserOnline(const std::string& userId) {
    std::lock_guard<std::mutex> lock(usersMutex);
    auto userIt = users.find(userId);
    return (userIt != users.end() && userIt->second->status == STATUS_ONLINE);
}

void EnhancedChatSystem::updateUserActivity(const std::string& userId) {
    std::lock_guard<std::mutex> lock(usersMutex);
    auto userIt = users.find(userId);
    if (userIt != users.end()) {
        userIt->second->lastActiveTime = time(nullptr);
    }
} 